<?php

namespace app\controller\admin\genshinteam;

use app\model\api\genshin\GenshinMaterials;
use laytp\controller\Backend;
use laytp\library\CommonFun;
use laytp\library\Tree;

/**
 * 菜单控制器
 */
class Material extends Backend
{
    public $model;
    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public function _initialize()
    {
        $this->model = new GenshinMaterials();
    }

    public function index()
    {
        $where   = $this->buildSearchParams();
        $order   = $this->buildOrder();
        $allData = $this->request->param('all_data');
        if ($allData) {
            $data = $this->model->where($where)->order($order)->cache(true)->select()->toArray();
//            $param = input("param.");
//            if(isset($param['type'])&&$param['type']=='radio'){
//                array_unshift($data,['materials_id'=>'','name'=>'请选择']);
//            }

        } else {
            $limit = $this->request->param('limit', 10);
            $data  = $this->model->where($where)->order($order)->paginate($limit)->toArray();
        }
        return $this->success('数据获取成功', $data);
    }

    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());

        $insData['name'] = $post['name'];
        $insData['icon']  = $post['icon'];
        $rand=rand(200000,999999);

        $insData['materials_id']  = $rand;
        $insData['type']  = $post['type'];
        try {
            $save = $this->model->save($insData);
            if (!$save) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
    public function rand($rand){
        $rand=rand(200000,999999);
        $mat_id=(new GenshinMaterials())->where('materials_id',$rand);
        if ($mat_id){
           $this->rand($rand);
        }else{
           $rand=$rand;
        }
        return $rand;
    }

    //编辑
    public function edit()
    {
        $id = $this->request->param('id');
        $post = CommonFun::filterPostData($this->request->post());
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $row->name = $post['name'];
        $row->icon  = $post['icon'];
        $row->type  = $post['type'];
        try {
            $save = $row->save();
            if ($save === false) throw new \Exception('保存失败');
            $this->clearCache();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
